<?php

namespace app\api\controller;

use app\facade\Redis;
use app\models\{Recpeople, RecpeopleArea, RecpeopleProject, BussinessSq, AgentArea, Wechat, User as Users, Business, Address, Region, Cart, Goods, GoodsSpec, Order, OrderGoods, Coupon, UserLevel, BusinessArea, Compent, Payment};
use think\Facade\Config as Configs;
use EasyWeChat\Factory;
use think\Validate;
use think\Db;
use think\facade\Log;

class User extends Base
{

    public function bussiness_res()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (empty($data['type'])) {
                $this->result([], 1, '入驻类型不能为空');
            }
            if ($data['type'] == 1) {
                $validate = new Validate([
                    'name' => 'require',
                    'cards' => 'require',
                    'mobile' => 'require',
                    'images1' => 'require',
                    'images2' => 'require',
                    'city' => 'require',
                    'area' => 'require'
                ], [
                    'name.require' => '用户名不能为空',
                    'cards.require' => '身份证号不能为空',
                    'mobile.require' => '联系电话不能为空',
                    'images1.require' => '身份证正面不能为空',
                    'images2.require' => '身份证反面不能为空',
                    'city.require' => '城市ID不能为空',
                    'area.require' => '区域ID不能为空',
                ]);
            } elseif ($data['type'] == 2) {
                $validate = new Validate([
                    'name' => 'require',
                    'cards' => 'require',
                    'mobile' => 'require',
                    'images1' => 'require',
                    'city' => 'require',
                    'area' => 'require'
                ], [
                    'name.require' => '公司(店铺)名称不能为空',
                    'cards.require' => '信用代码不能为空',
                    'mobile.require' => '联系电话不能为空',
                    'images1.require' => '营业执照不能为空',
                    'city.require' => '城市ID不能为空',
                    'area.require' => '区域ID不能为空',
                ]);
            } else {
                $this->result([], 1, '类型错误');
            }
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            if (!empty($data['street'])) {
                $street = (new Region())->where(['id' => $data['street'], 'level' => 4])->find();
                if (empty($street)) {
                    $this->result([], 1, '街道ID错误');
                }
                $area = (new Region())->where(['id' => $street['parent_id'], 'level' => 3])->find();
                if (empty($area)) {
                    $this->result([], 1, '区域ID错误');
                }
                $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
                if (empty($city)) {
                    $this->result([], 1, '城市ID错误');
                }
                $province = (new Region())->where(['id' => $city['parent_id'], 'level' => 1])->find();
                if (empty($province)) {
                    $this->result([], 1, '省份ID错误');
                }
                $data['area'] = $area['area_code'];
                $data['city'] = $city['area_code'];
                $data['province'] = $province['area_code'];
            } else {
                $area = (new Region())->where(['area_code' => $data['area'], 'level' => 3])->find();
                if (empty($area)) {
                    $this->result([], 1, '区域ID错误');
                }
                $city = (new Region())->where(['id' => $area['parent_id'], 'level' => 2])->find();
                if (empty($city)) {
                    $this->result([], 1, '城市ID错误');
                }
                $province = (new Region())->where(['id' => $city['parent_id'], 'level' => 1])->find();
                if (empty($province)) {
                    $this->result([], 1, '省份ID错误');
                }
                $data['street'] = 0;
                $data['area'] = $area['area_code'];
                $data['city'] = $city['area_code'];
                $data['province'] = $province['area_code'];
            }
            //查询
            if ($data['street'] == 0) {
                $agentarea = (new AgentArea())->whereOr(function ($query) use ($data) {
                    $query->where(['type' => 1]);
                })->whereOr(function ($query) use ($data) {
                    $query->where(['type' => 2, 'city' => $data['city']]);
                })->whereOr(function ($query) use ($data) {
                    $query->where(['type' => 3, 'area' => $data['area']]);
                })->find();
                $data['types'] = 3;
            } else {
                $agentarea = (new AgentArea())->whereOr(function ($query) use ($data) {
                    $query->where(['type' => 1]);
                })->whereOr(function ($query) use ($data) {
                    $query->where(['type' => 2, 'city' => $data['city']]);
                })->whereOr(function ($query) use ($data) {
                    $query->where(['type' => 3, 'area' => $data['area']]);
                })->whereOr(function ($query) use ($data) {
                    $query->where(['type' => 4, 'street' => $data['street']]);
                })->find();
                $data['types'] = 4;
            }
            if (empty($agentarea)) {
                $this->result([], 1, '所在区域未开通');
            }
            $data['user_id'] = $this->request->user_id;
            $data['status'] = 1;
            $business = (new BussinessSq())->where(['user_id' => $this->request->user_id, 'status' => [1, 3]])->find();
            if (empty($business)) {
                $res = (new BussinessSq())->allowfield(true)->save($data);
            } else {
                $res = (new BussinessSq())->allowfield(true)->save($data, ['id' => $business['id']]);
            }
            if ($res) {
                $this->result([], 0, '提交成功，请等待审核');
            }
            $this->result([], 1, '申请失败，请重试');
        } else {
            $regionmodel = new Region();
            $results = (new BussinessSq())->where(['user_id' => $this->request->user_id])->find();
            if ($results) {
                $results['province_name'] = $regionmodel->where(['area_code' => $results['province'], 'level' => 1])->value('name') ?? '';
                $results['city_name'] = $regionmodel->where(['area_code' => $results['city'], 'level' => 2])->value('name') ?? '';
                $results['area_name'] = $regionmodel->where(['area_code' => $results['area'], 'level' => 3])->value('name') ?? '';
                $results['street_name'] = $regionmodel->where(['id' => $results['street'], 'level' => 4])->value('name') ?? '';
            }
            $this->result($results, 0, '获取成功');
        }
    }

    public function buyuser()
    {
        $level = $this->request->post('level/d', 1);
        if ($this->request->user['level'] >= $level) {
            $this->result([], 1, '您已经是当前级别会员');
        }
        $level = (new UserLevel())->where('level', $level)->find();
        if (empty($level)) {
            $this->result([], 1, '信息参数错误');
        }
        $level['coupon'] = json_decode($level['coupon'], true);
        if ($level['days'] <= 0) {
            $this->result([], 1, '信息参数错误');
        }
        //支付订单 返回微信信息
        $ordersn = repayorder(new Payment());
        $wechatarr = [
            'pay_title' => '会员订单支付',
            'payment_id' =>  $ordersn,
            'money' => $level['money'],
            'ip' => $this->request->ip(),
            'user_id' => $this->request->user_id,
            'params' => json_encode(['trade_type' => 'JSAPI'], true)
        ];
        $parmes = [
            'user_id' => $this->request->user_id,
            'zhekou' => $level['zhekou'],
            'money' => $level['money'],
            'coupon' => $level['coupon'],
            'days' => $level['days'],
            'level' => $level['level']
        ];
        $parmes = json_encode($parmes, true);
        $list = (new Wechat())->pay($wechatarr);
        if ($list['status'] == true) {
            //存储支付订单记录
            $res = (new Payment())->save(['money' => $level['money'], 'type' => 2, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => 0, 'parmes' => $parmes, 'paytype' => 1]);
            if ($res) {
                $this->result($list, 0, '获取成功');
            } else {
                $this->result([], 1, '获取失败,请重试');
            }
        } else {
            $this->result([], 1, $list['msg'] ?? '获取失败');
        }
    }

    public function qrcode()
    {
        $name = 'appcode' . $this->request->user_id . '.png';
        $qcode = url('/uploads/wechat/' . $name, '', '', true);
        $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/wechat/";
        if (!file_exists($path . $name)) {
            $user = $this->request->user;
            $config = config('wechat.');
            $app = Factory::miniProgram($config);
            $rm = $app->app_code->getUnlimit('invite=' . $user['code'], [
                'page'  => '',
                'width' => 600,
            ]);
            if ($rm instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $rm->save($path, $name);
            }
        }
        $this->result($qcode, 0, '获取成功');
    }

    public function orderstatus()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'id' => 'require',
            'status' => 'require|in:2,4,5'
        ], [
            'id.require' => '订单ID不能为空',
            'status.require' => '状态不能为空',
            'status.in' => '状态不正确',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $order = (new Order())->where('id', $data['id'])->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        switch ($data['status']) {
            case '2':
                if ($order['status'] != 1) {
                    $this->result([], 1, '订单不处于支付状态');
                }
                //支付订单 返回微信信息
                $ordersn = repayorder(new Payment());
                $wechatarr = [
                    'pay_title' => '服务订单支付',
                    'payment_id' =>  $ordersn,
                    'money' => $order['total'],
                    'ip' => $this->request->ip(),
                    'user_id' => $this->request->user_id,
                    'params' => json_encode(['trade_type' => 'JSAPI'], true)
                ];
                $list = (new Wechat())->pay($wechatarr);
                if ($list['status'] == true) {
                    //存储支付订单记录
                    $res = (new Payment())->save(['money' => $order['total'], 'type' => 1, 'status' => 1, 'paymentid' => $ordersn, 'ordersn' => $order['ordersn']]);
                    if ($res) {
                        $this->result($list, 0, '获取成功');
                    } else {
                        $this->result([], 1, '获取失败,请重试');
                    }
                } else {
                    $this->result([], 1, $list['msg'] ?? '获取失败');
                }
                break;
            case '4':
                if ($order['status'] != 3) {
                    $this->result([], 1, '订单状态不可完成');
                }
                //完成订单
                $res = (new Order())->where('id', $data['id'])->update(['status' => $data['status'], 'finishtimes' => date('Y-m-d H:i:s')]);
                if ($res) {
                    $this->result([], 0, '操作成功');
                }
                $this->result([], 1, '操作失败，请重试');
                break;
            case '5':
                if ($order['status'] != 1 && $order['status'] != 2) {
                    $this->result([], 1, '订单状态不可取消');
                }
                if ($order['shouhou'] != 1) {
                    $this->result([], 1, '订单处于售后状态或已售后');
                }
                //取消
                if ($order['status'] == 1 || $order['status'] == 2) {
                    $shouhou = 1;
                    $status = $data['status'];
                    $tuikuan = 0;
                    $msg = '取消成功';
                    if ($order['status'] == 2 && $order['total'] > 0) {
                        $shouhou = 2;
                        $status = $order['status'];
                        $msg = '订单已提交';
                        $tuikuan = 2;
                    }
                    Db::startTrans();
                    try {
                        if ($order['coupon'] > 0 && $status == 5) {
                            (new Coupon())->where('id', $order['coupon'])->update(['status' => 1]);
                        }
                        (new Order())->where('id', $data['id'])->update([
                            'status' => $status,
                            'text' => $data['text'],
                            'shouhou' => $shouhou,
                            'tuikuan' => $tuikuan,
                            'caceltimes' => date('Y-m-d H:i:s')
                        ]);
                        Db::commit();
                        if ($order['status'] == 2 && $order['total'] > 0) {
                            Redis::lPush('tuikuan', $order['id']);
                        }
                    } catch (\Exception $e) {
                        dump($e->getMessage());
                        Db::rollback();
                        $this->result([], 1, '操作失败，请重试');
                    }
                    $this->result([], 0, $msg);
                }
                break;
            default:
                $this->result([], 1, '状态出错');
                break;
        }
    }

    public function goodscompent()
    {
        $goodsid = $this->request->get('goodsid/d', 0);
        $specid = $this->request->get('specid/d', 0);
        $list = (new Compent())->where('goodsid', $goodsid);
        if (!empty($specid)) {
            $list = $list->where('specid', $specid);
        }
        $list = $list->field('id,user_id,star,text,images,nickName,avatarUrl,created')->where('isshow', 1)->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            if (empty($lists['nickName'])) {
                $lists['user'] = (new Users())->where('id', $lists['user_id'])->field('nickName,avatarUrl')->find();
            } else {
                $user['nickName'] = $lists['nickName'];
                $user['avatarUrl'] = $lists['avatarUrl'];
                $lists['user'] = $user;
            }
            $lists['images'] = json_decode($lists['images'], true);
        }
        $this->result($list, 0, '获取成功');
    }

    public function compent()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'ordergoodsid' => 'require',
            'star' => 'require',
            'text' => 'require',
        ], [
            'ordergoodsid.require' => '订单规格ID不能为空',
            'star.require' => '评价星级不能为空',
            'text.require' => '评价内容不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (!empty($data['images'])) {
            $images = json_decode($data['images'], true) ?? [];
            if (count($images) == 0) {
                $this->result([], 1, '图片上传出错');
            }
        }
        $ordergoods = (new OrderGoods())->where(['id' => $data['ordergoodsid']])->find();
        if (empty($ordergoods)) {
            $this->result([], 1, '订单规格不存在');
        }
        if ($ordergoods['iscompent'] == 2) {
            $this->result([], 1, '您已评价，无需重复评价');
        }
        $order = (new Order())->where('ordersn', $ordergoods['ordersn'])->where('user_id', $this->request->user_id)->find();
        if (empty($order)) {
            $this->result([], 1, '订单不存在');
        }
        if ($order['status'] != 4) {
            $this->result([], 1, '订单状态未完成');
        }
        Db::startTrans();
        try {
            (new OrderGoods())->where(['id' => $data['ordergoodsid']])->update(['iscompent' => 2]);
            (new Compent())->allowfield(true)->save([
                'user_id' => $this->request->user_id,
                'ordergoodsid' => $ordergoods['id'],
                'goodsid' => $ordergoods['goodsid'],
                'specid' => $ordergoods['goodspecid'],
                'businessid' => $ordergoods['businessid'],
                'star' => $data['star'] ?? 5,
                'text' => $data['text'] ?? '很不错!',
                'images' => $data['images'] ?? ''
            ]);
            $ordercount = (new OrderGoods())->where(['ordersn' => $ordergoods['ordersn'], 'iscompent' => 1])->count();
            if ($ordercount == 0) {
                (new Order())->where('ordersn', $ordergoods['ordersn'])->update(['ispj' => 2]);
            }
            Db::commit();
            if ($data['star'] > 3) {
                (new Goods())->where('id', $ordergoods['goodsid'])->setInc('goodspj');
            }
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '评价失败');
        }
        $this->result([], 0, '评价成功');
    }

    public function orderdetail()
    {
        $id = $this->request->get('id/d', 0);
        $list = (new Order())->where('id', $id)->field('putorder,coupon,payment,paytimes,fwtimes,finishtimes,caceltimes', true)->find();
        if ($list) {
            $list['status_text'] = $list->status_text;
            $list['province_text'] = (new Region())->where(['area_code' => $list['province']])->value('name');
            $list['city_text'] = (new Region())->where(['area_code' => $list['city']])->value('name');
            $list['area_text'] = (new Region())->where(['area_code' => $list['area']])->value('name');
            $list['street_text'] = (new Region())->where(['id' => $list['street']])->value('name');
            $goods = (new OrderGoods())->where('ordersn', $list['ordersn'])->field('id,ordersn,images,number,title,name,goodsid,goodspecid,price,unmit,iscompent')->select();
            foreach ($goods as $good) {
                $good['images'] = json_decode($good['images'], true);
            }
            $list['good'] = $goods;
        }
        $this->result($list, 0, '获取成功');
    }

    public function getorders()
    {
        $ordersn = $this->request->get('ordersn/d', 0);
        $list = (new OrderGoods())->where(['ordersn' => $ordersn])->select();
        $havegoods = [];
        foreach ($list as $lists) {
            $goods = (new Goods())
                ->alias('g')
                ->distinct(true)
                ->join('business b', 'g.businessid = b.id')
                ->join('goods_spec gs', 'gs.goodid= g.id')
                ->where(['gs.id' => $lists['goodspecid'], 'gs.isdel' => 1, 'g.isSale' => 1, 'g.isdel' => 1, 'b.status' => 1])
                ->field('g.id,g.type,g.title,g.starbuy,g.images,g.times,gs.id as specid,gs.price,gs.name,gs.stock,gs.unmit')->find();
            if (!empty($goods)) {
                $goods['number'] = $lists['number'];
                if ($lists['number'] < $goods['starbuy']) {
                    $goods['number'] = $goods['starbuy'];
                }
                $goods['images'] = json_decode($goods['images'], true);
                $havegoods = $goods;
            }
        }
        $this->result($havegoods, 0, '获取成功');
    }

    public function getcoupon()
    {
        $data = $this->request->get();
        $list = (new Coupon())->where(['user_id' => $this->request->user_id, 'status' => 1])->order('money desc')->select();
        $total = 0;
        $businessid = 0;
        if (!empty($data['specid'])) {
            $data['specid'] = json_decode($data['specid'] ?? '', true);
            if (empty($data['specid'])) {
                $this->result([], 1, '规格数据错误');
            }
            foreach ($data['specid'] as $spec) {
                if (empty($spec['id'])  || empty($spec['number'])) {
                    continue;
                }
                //查询规格是否存在
                $goodspec = (new GoodsSpec())->where(['isdel' => 1, 'id' => $spec['id']])->find();
                if (empty($goodspec)) {
                    continue;
                }
                //判断商品是否下架
                $goods = (new Goods())->where(['isdel' => 1, 'isSale' => 1, 'id' => $goodspec['goodid']])->find();
                if (empty($goods)) {
                    continue;
                }
                //判断商户是否正常
                $business = (new Business())->where(['id' => $goods['businessid'], 'status' => 1])->find();
                if (empty($business)) {
                    continue;
                }
                $businessid = $business['id'];
                $total += $goodspec['price'] * $spec['number'];
            }
        }
        foreach ($list as $lists) {
            $lists['title'] = '平台通用券';
            $lists['iscan'] = 1;
            if ($lists['type'] == 2) {
                $lists['title'] = (new Business())->where('id', $lists['business'])->value('title') ?? '';
                if ($businessid == $lists['business'] && $total >= $lists['getmoney']) {
                    $lists['iscan'] = 2;
                }
            }
            if ($lists['type'] == 1) {
                if ($total >= $lists['getmoney']) {
                    $lists['iscan'] = 2;
                }
            }
        }
        //优惠券减免
        $this->result($list, 0, '获取成功');
    }

    public function putorder()
    {
        $data = $this->request->post();
        $validate = new Validate([
            'specid' => 'require',
            'addressid' => 'require'
        ], [
            'specid.require' => '规格ID不能为空',
            'addressid.require' => '地址ID不能为空',
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        $data['times'] = date('Y-m-d H:i', strtotime($data['times'])) ?? date('Y-m-d H:i:s');
        $data['specid'] = json_decode($data['specid'] ?? '', true);
        if (empty($data['specid'])) {
            $this->result([], 1, '规格数据错误');
        }
        if (!empty($data['cartid'])) {
            $data['cartid'] = json_decode($data['cartid'] ?? '', true);
            if (empty($data['cartid'])) {
                $this->result([], 1, '购物车数据错误');
            }
        }
        //查询地址是否存在
        $address = (new Address())->where(['user_id' => $this->request->user_id, 'id' => $data['addressid']])->find();
        if (empty($address)) {
            $this->result([], 1, '地址不存在');
        }
        $order = [
            'type' => 0,
            'user_id' => $this->request->user_id,
            'ordersn' => reordersn(new Order()),
            'businessid' => 0,
            'name' => $address['name'],
            'mobile' => $address['mobile'],
            'province' => $address['province'],
            'city' => $address['city'],
            'area' => $address['area'],
            'street' => $address['street'],
            'getaddress' => $address['getaddress'],
            'address' => $address['address'],
            'lat' => $address['lat'],
            'lon' => $address['lon'],
            'total' => 0,
            'coupon' => $data['coupon'] ?? 0,
            'times' => $data['times'],
            'remark' => $data['remark'] ?? '',
            'coupontotal' => 0,
            'zhekoutotal' => 0,
            'othertotal' => 0,
            'total' => 0,
            'ptotal' => 0
        ];
        $ordergoods = [];
        $sendmoney = 0; //起送金额
        foreach ($data['specid'] as $spec) {
            if (empty($spec['id'])  || empty($spec['number'])) {
                $this->result([], 1, '规格参数错误');
            }
            //查询规格是否存在
            $goodspec = (new GoodsSpec())->where(['isdel' => 1, 'id' => $spec['id']])->find();
            if (empty($goodspec)) {
                $this->result([], 1, '规格已下架，请重新提交订单');
            }
            //判断商品是否下架
            $goods = (new Goods())->where(['isdel' => 1, 'isSale' => 1, 'id' => $goodspec['goodid']])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品已下架');
            }
            // if ($goods['type'] == 3 && $goodspec['stock'] < $spec['number']) {
            //     $this->result([], 1, '库存不足');
            // }
            //判断商户是否正常
            $business = (new Business())->where(['id' => $goods['businessid']])->find();
            if (empty($business) || $business['status'] != 1) {
                $this->result([], 1, '商家已下架');
            }
            if ($business['shows'] != 1) {
                $this->result([], 1, '超出服务范围');
            }
            if ($goods['type'] == 1 || $goods['type'] == 2) {
                $fwtime = $business['fwtime'] ?? '00:00 - 24:00';
                $fwtime = explode('-', $fwtime);
                $start = $fwtime[0] ?? '00:00';
                $end = $fwtime[1] ?? '22:00';
                //最早时间计算
                $zuizao = date('H', time() + 1800 + $goods['times'] * 60) . ':00';
                //如果超越了营业时间可预约明天
                if (strtotime($zuizao) > strtotime($end)) {
                    $zuizao = date('Y-m-d ', time() + 86400) . $start;
                } else {
                    $zuizao = date('Y-m-d ') . $zuizao;
                }
                if ($data['times'] < $zuizao) {
                    $this->result([], 1, '预约时间不能早于' . $zuizao);
                }
            }
            if (empty($order['type'])) {
                $order['type'] = $goods['type'];
            } elseif ($order['type'] != $goods['type']) {
                $this->result([], 1, '不同类型商品不可同时下单');
            }
            if (empty($order['businessid'])) {
                $order['businessid'] = $goods['businessid'];
            } elseif ($order['businessid'] != $goods['businessid']) {
                $this->result([], 1, '不同商家商品不可同时下单');
            }
            $sendmoney = $business['sendmoney'];
            if ($goods['type'] == 1 && count($data['specid']) > 1) {
                $this->result([], 1, '技术服务类型项目不可与其它混合项目一起结算');
            }
            //查找下面有没有相关服务人员
            $order['ptotal'] += $goodspec['price'] * $spec['number'];
            $ordergoods[] = [
                'ordersn' => $order['ordersn'],
                'businessid' => $goods['businessid'],
                'classid' => $goods['classid'],
                'sonsid' => $goods['sonsid'],
                'goodsid' => $goods['id'],
                'goodspecid' => $goodspec['id'],
                'title' => $goods['title'],
                'images' => $goods['images'],
                'name' => $goodspec['name'],
                'number' =>  $spec['number'],
                'unmit' => $goodspec['unmit'],
                'price' =>   $goodspec['price'],
                'total' => floor($spec['number'] * $goodspec['price'] * 100) / 100
            ];
        }
        if ($order['total'] < $sendmoney) {
            $this->result([], 1, '总价低于商家起送价格' . $sendmoney . '元，下单失败');
        }
        $order['total'] = $order['ptotal'];
        //折扣减免
        $zhekou = (new UserLevel())->where('level', $this->request->user['level'])->value('zhekou') ?? 100;
        if ($zhekou > 100) {
            $zhekou = 100;
        }
        //优惠券减免
        if (!empty($data['coupon'])) {
            $coupon = (new Coupon())->where(['id' => $data['coupon'], 'user_id' => $this->request->user_id, 'status' => 1])->find();
            if (empty($coupon)) {
                $this->result([], 1, '优惠券不存在或已使用');
            }
            if ($coupon['type'] == 2 && $coupon['business'] != $order['businessid']) {
                $this->result([], 1, '优惠券在该商户平台不可用');
            }
            if ($coupon['getmoney'] > $order['ptotal']) {
                $this->result([], 1, '优惠券未达到使用条件');
            }
            if ($coupon['money'] > $order['total']) {
                $order['coupontotal'] = $order['total'];
                $order['total'] = 0;
            } else {
                $order['coupontotal'] = $coupon['money'];
                $order['total'] -= $coupon['money'];
            }
        }
        if ($order['type'] == 1 || $order['type'] == 2 || $order['type'] == 3) {
            //商家服务地址检测
            $businessarea = (new BusinessArea())->whereOr(function ($query) use ($order, $address) {
                $query->where(['type' => 1, 'businessid' => $order['businessid']]);
            })->whereOr(function ($query) use ($order, $address) {
                $query->where(['type' => 2, 'businessid' => $order['businessid'], 'city' => $address['city']]);
            })->whereOr(function ($query) use ($order, $address) {
                $query->where(['type' => 3, 'businessid' => $order['businessid'], 'area' => $address['area']]);
            })->whereOr(function ($query) use ($order, $address) {
                $query->where(['type' => 4, 'businessid' => $order['businessid'], 'street' => $address['street']]);
            })->find();
            if (empty($businessarea)) {
                $this->result([], 1, '服务区域不在商家服务范围内');
            }
        }
        //折扣减免金额
        $order['zhekoutotal'] = floor((100 - $zhekou) * $order['ptotal']) / 100;
        if ($order['zhekoutotal'] > 0) {
            $order['total']  -= $order['zhekoutotal'];
        }
        if (count($ordergoods) < 1 || count($order) < 1) {
            $this->result([], 1, '结算出错,请重试');
        }
        if ($order['total'] == 0) {
            $order['status'] = 2;
        }
        Db::startTrans();
        try {
            $id = (new Order())->insertGetId($order);
            (new OrderGoods())->allowfield(true)->saveAll($ordergoods);
            if (!empty($data['cartid'])) {
                (new Cart())->where(['id' => $data['cartid'], 'user_id' => $this->request->user_id])->delete();
            }
            if (!empty($coupon)) {
                (new Coupon())->where(['id' => $coupon['id'], 'user_id' => $this->request->user_id, 'status' => 1])->update(['status' => 3]);
            }
            Db::commit();
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollback();
            $this->result([], 1, '下单失败');
        }
        $this->result(['id' => $id], 0, '下单成功');
    }

    public function orderlist()
    {
        $status = $this->request->get('status/d', '');
        $list = (new Order())->order('id desc');
        if (!empty($status)) {
            $list = $list->where('status', $status);
        }
        $list = $list->where('user_id', $this->request->user_id)->field('id,ordersn,businessid,status,total,ptotal,shouhou,tuikuan,type,created,ispj')->paginate(20, false, ['query' => $this->request->param()]);
        foreach ($list as $lists) {
            $lists['tnumber'] = 0;
            $lists['business_name'] = (new Business())->where('id', $lists['businessid'])->value('title');
            $ordergoods = (new OrderGoods())->where(['ordersn' => $lists['ordersn']])->field('id,title,name,unmit,goodspecid,images,number,iscompent,price')->select();
            foreach ($ordergoods as $goods) {
                $lists['tnumber'] += $goods['number'];
                $goods['images'] = json_decode($goods['images'] ?? '', true);
            }
            $lists['goods'] = $ordergoods;
            $lists['status_text'] = $lists->status_text;
        }
        $this->result($list, 0, '获取成功');
    }

    public function cart()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'goodsid' => 'require',
                'specid' => 'require',
                'number' => 'require',
            ], [
                'goodsid.require' => '商品ID不能为空',
                'specid.require' => '商品规格不能为空',
                'number.require' => '商品数目不能为空'
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $goods = (new Goods())->where(['id' => $data['goodsid'], 'isSale' => 1, 'isdel' => 1])->find();
            if (empty($goods)) {
                $this->result([], 1, '商品已下架');
            }
            // if ($goods['type'] == 1) {
            //     $this->result([], 1, '该类型产品不可加入购物车');
            // }
            $business = (new Business())->where(['id' => $goods['businessid'], 'status' => 1])->find();
            if (empty($business)) {
                $this->result([], 1, '商家已下架');
            }
            $goodsspec = (new GoodsSpec())->where(['isdel' => 1, 'goodid' => $goods['id'], 'id' => $data['specid']])->find();
            if (empty($goodsspec)) {
                $this->result([], 1, '规格产品已下架');
            }
            //查询是否已经添加购物车
            $mycart = (new Cart())->where(['specid' => $data['specid'], 'user_id' => $this->request->user_id])->find();
            //购物车商品数量不能超过20个
            if (empty($mycart)) {
                $carts = (new Cart())->where(['user_id' => $this->request->user_id])->count();
                if ($carts >= 15) {
                    $this->result([], 1, '您的购物车产品数量已达到15个,请先结算或清空购物车');
                }
            }
            $number = (int)$data['number'] ?? 0;
            $goods['starbuy'] = $goods['starbuy'] > 1 ? $goods['starbuy'] : 1;
            if (!empty($mycart)) {
                $number += $mycart['number'];
            }
            if ($number <  $goods['starbuy']) {
                $this->result([], 1, '起购数量不能低于' . $goods['starbuy']);
            }
            $save = [
                'user_id' => $this->request->user_id,
                'business' => $business['id'],
                'goodsid' => $goods['id'],
                'specid' => $goodsspec['id'],
                'number' => $number
            ];
            if (!empty($mycart)) {
                $res =  (new Cart())->allowfield(true)->save($save, ['id' => $mycart['id']]);
            } else {
                $res =  (new Cart())->allowfield(true)->save($save);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $list = (new Cart())->where(['user_id' => $this->request->user_id])->select();
            $results = [];
            foreach ($list as $lists) {
                $good = (new Goods())->where(['id' => $lists['goodsid']])->where(['isSale' => 1, 'isdel' => 1])->field('id,title,images,type,starbuy')->find();
                $goodspec = (new GoodsSpec())->where('isdel', 1)->where(['id' => $lists['specid']])->field('name,price,unmit')->find();
                $goods = [];
                if (!empty($good['type']) && $good['type'] == 1) {
                    $key = $lists['business'] . $good['type'] . $good['id'] ?? 0;
                } else {
                    $key = $lists['business'] . $good['type'] ?? 0;
                }
                $results[$key]['businessid'] = $lists['business'];
                if (empty($results[$key]['name'])) {
                    $results[$key]['name'] = (new Business())->where(['id' => $lists['business']])->value('title');
                }
                $goods = [
                    'cartid' => $lists['id'],
                    'goodsid' => $lists['goodsid'],
                    'starbuy' => $good['starbuy'],
                    'specid' => $lists['specid'],
                    'title' => $good['title'] ?? '商品已下架',
                    'images' => json_decode($good['images'] ?? '', true) ?? [],
                    'spectitle' => $goodspec['name'] ?? '规格已下架',
                    'price' => $goodspec['price'] ?? 0,
                    'unmit' => $goodspec['unmit'] ?? '',
                    'type' => $good['type'] ?? 0,
                    'number' => $lists['number']
                ];
                if (empty($results[$key]['total'])) {
                    $results[$key]['total'] = $goods['price'];
                } else {
                    $results[$key]['total'] += $goods['price'];
                }
                $results[$key]['total'] = floor($results[$key]['total'] * 100) / 100;
                $results[$key]['good'][] = $goods;
            }
            $results = array_merge($results);
            $this->result($results, 0, '获取成功');
        }
    }

    public function cart_del()
    {
        $id = $this->request->post('id', '');
        $id = json_decode($id, true);
        if (count($id) <= 0) {
            $this->result([], 1, '操作失败');
        }
        $cartmodel = new Cart();
        $result = $cartmodel->where(['user_id' => $this->request->user_id, 'id' => $id])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }

    public function info()
    {
        $user = $this->request->user;
        $result = [
            'id' => $user['id'],
            'code' => $user['code'],
            'nickName' => $user['nickName'],
            'gender' => $user['gender'],
            'avatarUrl' => $user['avatarUrl'],
            'mobile' => $user['mobile'],
            'money' => 0,
            'level_time' => $user['level_time'],
            'level' => $user['level'],
            'zhekou' => (new UserLevel())->where('level', $user['level'])->value('zhekou') ?? 100,
            'coupn' => (new Coupon())->where(['user_id' => $this->request->user_id, 'status' => 1])->count(),
        ];
        $this->result($result, 0, '获取成功');
    }

    public function login()
    {
        // Redis::setex('123456', 86400, 1);
        $data = $this->request->post();
        $validate = new Validate([
            'code' => 'require',
            'iv' => 'require',
            'encryptedData' => 'require',
        ], [
            'code.require' => '微信授权码不能为空',
            'iv.require' => 'IV数据不能为空',
            'encryptedData.require' => 'encryptedData数据不能为空'
        ]);
        if (!$validate->check($data)) {
            $this->result([], 1, $validate->getError());
        }
        if (!empty($data['bunessid'])) {
            $business = (new Business())->where('id', $data['bunessid'])->find();
            if (empty($business)) {
                $this->result([], 1, '商户不存在');
            }
        }
        $model = new Users();
        $config = config('wechat.');
        $app = Factory::miniProgram($config);
        try {
            $res = $app->auth->session($data['code']);
        } catch (\Exception $e) {
            $this->result([], 1, '信息错误');
        }
        $time = $config['tokenExpireHours'];
        if (empty($res['session_key']) || empty($res['unionid']) || empty($res['openid'])) {
            $this->result([], 1, '登录失败,请重试');
        }
        //判断用户是否已经注册
        $user = $model->where('unionid', $res['unionid'])->find();
        try {
            $decryptedData = $app->encryptor->decryptData($res['session_key'], $data['iv'], $data['encryptedData']);
        } catch (\Exception $e) {
            $this->result([], 1, $e->getMessage());
        }

        $save = [
            'unionid' => $res['unionid'],
            'session_key' => $res['session_key'],
            'openid' => $res['openid'],
            'business' => $business['id'] ?? 0,
            'shopid' => $data['shopid'] ?? 0,
            'gender' => $decryptedData['gender'] ?? 0,
            'province' => $decryptedData['province'] ?? '',
            'city' => $decryptedData['city'] ?? '',
            'avatarUrl' => $decryptedData['avatarUrl'] ?? '',
            'country' => $decryptedData['country'] ?? '',
            'nickName' =>  preg_replace('/[\xf0-\xf7].{3}/', '', $decryptedData['nickName'] ?? ''),
        ];
        if ($user) {
            $res2 = (new Users())->allowfield(true)->save($save, ['id' => $user['id']]);
        } else {
            $save['code'] = recode($model);
            $res2 = (new Users())->allowfield(true)->save($save);
            $user = (new Users())->where('unionid', $res['unionid'])->find();
        }
        if ($res2 && !empty($user)) {
            $token = 'user_' . md5(time() . $user['code']);
            Redis::setex($token, $time, $user['id']);
            $this->result(['token' => $token], 0, '登录成功');
        }

        $this->result([], 1, '登录失败');
    }


    public function address()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'name' => 'require',
                'mobile' => 'require',
                'street' => 'require',
                'address' => 'require',
                'is_default' => 'require|in:1,2',
                'getaddress' => 'require',
                'lat' => 'require',
                'lon' => 'require',
            ], [
                'name.require' => '联系人姓名不能为空',
                'mobile.require' => '联系人电话不能为空',
                'street.require' => '街道ID不能为空',
                'address.require' => '具体地址不能为空',
                'getaddress.require' => '定位地址不能为空',
                'is_default.require' => '默认类型不能为空',
                'is_default.in' => '默认类型不正确',
                'lat.require' => '经度不能为空',
                'lon.require' => '纬度不能为空',
            ]);
            if (!$validate->check($data)) {
                $this->result([], 1, $validate->getError());
            }
            $regionmodel = new Region();
            $street = $regionmodel->where(['id' => $data['street'], 'level' => 4])->find();
            if (!$street) {
                $this->result([], 1, '街道编码出错');
            }
            $area = $regionmodel->where(['id' => $street['parent_id'], 'level' => 3])->find();
            if (!$area) {
                $this->result([], 1, '区域编码出错');
            }
            $city = $regionmodel->where(['id' => $area['parent_id'], 'level' => 2])->find();
            if (!$city) {
                $this->result([], 1, '城市编码出错');
            }
            $province = $regionmodel->where(['id' => $city['parent_id'], 'level' => 1])->find();
            if (!$province) {
                $this->result([], 1, '省份编码出错');
            }
            $data['street'] = $street['id'];
            $data['area'] = $area['area_code'];
            $data['city'] = $city['area_code'];
            $data['province'] = $province['area_code'];
            $data['user_id'] = $this->request->user_id;
            $addressmodel = new Address();
            if ($data['is_default'] == 2) {
                $addressmodel->where(['user_id' => $data['user_id'], 'is_default' => 2])->update(['is_default' => 1]);
            }
            if (!empty($data['id'])) {
                $res = $addressmodel->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                $res = $addressmodel->allowfield(true)->save($data);
            }
            if ($res) {
                $this->result([], 0, '操作成功');
            }
            $this->result([], 1, '操作失败');
        } else {
            $addressmodel = new Address();
            $regionmodel = new Region();
            $result = $addressmodel->where('user_id', $this->request->user_id)->order('is_default desc')->field('user_id,created', true)->select();
            foreach ($result as $results) {
                $results['province_name'] = $regionmodel->where(['area_code' => $results['province'], 'level' => 1])->value('name');
                $results['city_name'] = $regionmodel->where(['area_code' => $results['city'], 'level' => 2])->value('name');
                $results['area_name'] = $regionmodel->where(['area_code' => $results['area'], 'level' => 3])->value('name');
                $results['street_name'] = $regionmodel->where(['id' => $results['street'], 'level' => 4])->value('name');
            }
            $this->result($result, 0, '操作成功');
        }
    }


    public function address_del()
    {
        $id = $this->request->post('id/d', 0);
        $addressmodel = new Address();
        $result = $addressmodel->where(['user_id' => $this->request->user_id, 'id' => $id])->delete();
        if ($result) {
            $this->result([], 0, '操作成功');
        }
        $this->result([], 1, '操作失败');
    }
}
